/**
 * Copyright 2009 University of Washington This code is released under the GPL version 3 - with a copy of the license
 * included
 * 
 * @author Maya Hao Li
 * 
 */
package seedpod.rdb;

public class SqlUtil {
	public static final int MAX_NAME_CHAR_LENGTH = 63;
	public static final String TAB = "\t";/* tab */
	public static final String NL = "\n"; /* new line */
	public static final String SP = " "; /* space */
	public static final String C = ", "; /* comma */
	public static final String SC = "; "; /* semicolon */

	/**
	 * escape single quotes
	 * 
	 * @param string
	 * @return
	 */
	public static String addslashes( String string ) {

		return string.replaceAll( "'", "\'" );
	}

	public static String C( String s ) {
		return s + ", ";
	}

	/**
	 * dollarquote string
	 * 
	 * @param val
	 * @return
	 */
	public static String dollarQuote( String val, String customquote ) {
		if ( val == null || val.equalsIgnoreCase( "null" ) ) return val;

		val = escapeSingleQuote( val );
		if ( customquote == null ) customquote = "$sp$";
		if ( customquote.charAt( 0 ) != '$' ) customquote = "$" + customquote;
		if ( customquote.charAt( customquote.length() - 1 ) != '$' ) customquote = customquote + "$";
		return customquote + val + customquote;
	}

	public static String DQ( String string ) {
		return dollarQuote( string, null );
	}

	/**
	 * postgres can only takes 63 characters for a table name or an attribute name. This function will clean up the
	 * empty beginning and ending spaces, and truncate the string
	 * 
	 * @param name
	 * @return String name that's at most 63 characters long
	 */
	public static String ensureProperLength( String name ) {
		name = name.trim();
		if ( name.length() > MAX_NAME_CHAR_LENGTH ) name = name.substring( 0, MAX_NAME_CHAR_LENGTH );
		return name;
	}

	public static String escapeSingleQuote( String val ) {
		return val.replaceAll( "'", "''" );
	}

	public static String PARAN( String s ) {
		return "(" + s + ")";
	}

	public static StringBuffer PARAN( StringBuffer s ) {
		s.insert( 0, "(" );
		s.insert( s.length(), ")" );
		return s;
	}

	public static String Q( String s ) {
		return "'" + s + "' ";
	}

	// quote and comma
	public static String QC( String s ) {
		return "'" + s + "', ";
	}

	public static String QQ( String s ) {
		return "\"" + s + "\"";
	}

}
